package com.cmccgz.udacs_landlord_webapp.update;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.apache.http.entity.StringEntity;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.cmccgz.udacs_landlord_webapp.base.ApiService;
import com.cmccgz.udacs_landlord_webapp.bean.AppInfo;
import com.cmccgz.udacs_landlord_webapp.bean.ResultBean;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import rx.Subscriber;

public class AppVersionUpdateUtil {
    public static final String appcodeMetaKey = "com.gmccgz.kakaonew.APP_CODE";
    public static final String charset = "utf-8";
    public static final int checkAppUpdateWhat = 0x101;

    /**
     * 检查更新
     *
     * @param handler
     * @param context
     */
    public static void checkAppVersionUpdate(final Handler handler, final Context context) {
        if (!NetUtil.isNetEnabled(context)) {
            return;
        }
        HttpUtils http = XutilsInstance.getHttpUtils();
        final String url = "http://" + AppConfig.APPUPDATE_SERVICE + "/get_appinfo";
        try {
            RequestParams params = new RequestParams();
            params.setBodyEntity(new StringEntity(getAppVersionUpdateXML(context), charset));
            Log.d("mxs", "升级请求 url=" + url + "\r\n" + getAppVersionUpdateXML(context));
            http.send(HttpMethod.POST, url, params, new RequestCallBack<String>() {

                @Override
                public void onFailure(HttpException arg0, String arg1) {
                    // TODO Auto-generated method stub
                    AppInfoBean bean = new AppInfoBean();

                    bean.setRetcode(-1);
                    Message msg = new Message();
                    msg.what = checkAppUpdateWhat;
                    msg.obj = bean;
                    handler.sendMessage(msg);
                }

                @Override
                public void onSuccess(ResponseInfo<String> arg0) {
                    // TODO Auto-generated method stub
                    AppInfoBean bean = parseData(arg0.result);
                    Log.d("mxs", "升级响应 url=" + url + "\r\n" + arg0.result);
                    Message msg = new Message();
                    msg.what = checkAppUpdateWhat;
                    msg.obj = bean;
                    handler.sendMessage(msg);
                }

            });
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * 检查更新
     * @param handler
     * @param context
     */
    public static void checkAppUpdate(final Handler handler, final Context context) {
        if (!NetUtil.isNetEnabled(context)) {
            return;
        }
        ApiService.getAppInfo(AppConfig.APP_CODE).subscribe(new Subscriber<ResultBean<AppInfo>>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                AppInfoBean bean = new AppInfoBean();
                bean.setRetcode(-1);
                Message msg = new Message();
                msg.what = checkAppUpdateWhat;
                msg.obj = bean;
                handler.sendMessage(msg);
            }

            @Override
            public void onNext(ResultBean<AppInfo> appInfoResultBean) {
                if ("0".equals(appInfoResultBean.rsmsg.rscode)) {
                    AppInfo appInfo = appInfoResultBean.resp;
                    AppInfoBean bean = parseData(context, appInfo);
                    Log.d("mxs", "升级响应 url=" + bean.getUrl());
                    Message msg = new Message();
                    msg.what = checkAppUpdateWhat;
                    msg.obj = bean;
                    handler.sendMessage(msg);
                } else {
                    AppInfoBean bean = new AppInfoBean();
                    bean.setRetcode(-1);
                    Message msg = new Message();
                    msg.what = checkAppUpdateWhat;
                    msg.obj = bean;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    /**
     * 获取升级xml
     *
     * @param context
     * @return
     */
    private static String getAppVersionUpdateXML(Context context) {
        String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<request>"

                + "<header>" + "<signature>" + getSignature(context) + "</signature>" + "<messageId>" + System.currentTimeMillis() + "</messageId>" + "</header>"

                + "<body>" + "<appCode>" + AppConfig.APP_CODE/* "201504150000" */ + "</appCode>" + "<version>" + PackageUtils.getAppVersionCode(context) + "</version>" + "</body>"

                + "</request>";

        return xmlStr;
    }

    /**
     * 获取signature
     *
     * @param context
     * @return
     */
    private static String getSignature(Context context) {
        String signature = "fromid:" + AppConfig.getMobile(context) + "," + "imsi:" + AppConfig.getIMSI(context) + "," + "imei:" + AppConfig.getIMEI(context) + "," + "token:" + AppConfig.getToken(context);
        return signature;
    }

    /**
     * 解析结果
     *
     * @param xmlStr
     * @return
     */
    private static AppInfoBean parseData(String xmlStr) {
        AppInfoBean bean = new AppInfoBean();

        if (xmlStr == null || "".equals(xmlStr)) {
            bean.setRetcode(-1);
            return bean;
        }
        byte[] bytes = xmlStr.getBytes();
        try {
            ByteArrayInputStream input = new ByteArrayInputStream(bytes);
            XmlPullParserFactory pull = XmlPullParserFactory.newInstance();
            pull.setNamespaceAware(true);
            XmlPullParser parser = pull.newPullParser();
            parser.setInput(input, "utf-8");
            int tagType = parser.getEventType();
            while (tagType != XmlPullParser.END_DOCUMENT) {
                if (tagType == XmlPullParser.START_TAG) {
                    if ("retcode".equals(parser.getName())) {
                        bean.setRetcode(Integer.parseInt(parser.nextText()));
                    } else if ("retmessage".equals(parser.getName())) {
                        bean.setRetmessage(parser.nextText());
                    } else if ("ifUpdate".equals(parser.getName())) {
                        bean.setIfUpdate(Integer.parseInt(parser.nextText()));
                    } else if ("version".equals(parser.getName())) {
                        bean.setVersion(parser.nextText());
                    } else if ("versionName".equals(parser.getName())) {
                        bean.setVersionName(parser.nextText());
                    } else if ("mustUpdate".equals(parser.getName())) {
                        bean.setMustUpdate(Integer.parseInt(parser.nextText()));
                    } else if ("url".equals(parser.getName())) {
                        bean.setUrl(parser.nextText());
                    } else if ("description".equals(parser.getName())) {
                        bean.setDesc(parser.nextText());
                    }

                }
                tagType = parser.next();
            }
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bean;

    }

    /**
     * 解析结果
     *
     * @param appInfo
     * @return
     */
    private static AppInfoBean parseData(Context context, AppInfo appInfo) {
        AppInfoBean bean = new AppInfoBean();
        if (appInfo == null) {
            bean.setRetcode(-1);
            return bean;
        }
        bean.setRetcode(0);
        bean.setRetmessage("成功");
        int versionCode = PackageUtils.getAppVersionCode(context);
        int vCode = Integer.parseInt(appInfo.getApp_version_seq());
        bean.setIfUpdate(vCode > versionCode ? 1 : 0);
        bean.setVersion(appInfo.getApp_version_seq());
        bean.setVersionName(appInfo.getApp_version());
        bean.setMustUpdate(Integer.parseInt(appInfo.getIs_force_upgrade()));
        bean.setUrl(appInfo.getPath());
        bean.setDesc(appInfo.getApp_version_desc());
        return bean;
    }
}
